# -*-coding:utf-8-*-
from django_redis import get_redis_connection
from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers

from books.models import Books
from books.search_index import BookIndex


class BookSerializer(serializers.ModelSerializer):
    """
    图书列表序列化器
    """

    class Meta:
        model = Books
        fields = ('id', 'name', 'scorce', 'image_url', 'comments','author')


class BookIndexSerializer(HaystackSerializer):
    """
    Book索引结果数据序列化器
    """
    object = BookSerializer(read_only=True)

    class Meta:
        index_classes = [BookIndex]
        fields = ("text", "object")


class BookHisrotySerializer(serializers.Serializer):
    """用户历史浏览记录序列化器"""
    book_id = serializers.IntegerField(label="book编号", min_value=1)

    def validated(self, attrs):
        """
        判断sku_id是否存在
        :param attrs:
        :return:
        """
        try:
            Books.objects.get(id=attrs["book_id"])
        except:
            raise serializers.ValidationError("图书不存在")
        return attrs

    def create(self, validated_data):
        """
        保存浏览历史数据到redis中
        1.建立redis链接
        2.判断book_id是否保存过
        3.保存错,删除;没保存过,写入book_id
        4.控制保存数量
        5.返回结果
        :param validated_data:
        :return:
        """

        # 1.建立连接
        conn = get_redis_connection('history')
        user = self.context['request'].user
        # 2.判断是否保存过
        conn.lrem("history_{}".format(user.id), 0, validated_data['book_id'])
        # 3.写入
        conn.lpush("history_{}".format(user.id), validated_data['book_id'])
        # 4.控制保存数量
        conn.ltrim("history_{}".format(user.id), 0, 6)
        # 5.返回
        return validated_data



